package cn.otrue.patienthealthmanager.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.activity.CenterInfoChangeActivity;
import cn.otrue.patienthealthmanager.http.HttpCons;

public class SendImageToServer {
	private String newName = "image.jpg";
	private String uploadFile;
	private String actionUrl = HttpCons.SAVEURL;
	
	private int WIN = 1;
	private String back;
	private Context context;
	private String name;
	private String respectively;
	public static List<String> imageName;

	public SendImageToServer(String uploadfile, Context context) {
		this.uploadFile = uploadfile;
		this.context = context;
	}

	/**
	 * 开启线程，开始上传头像
	 * @describe 由于需要获取姓名所以不在初始化该类时进行上传图片到服务器
	 * @author BGX
	 * @time 2015-4-26
	 */
	public void startThread() {
		try {
			ThreadManager.execute(new Runnable() {
				@Override
				public void run() {
					uploadFile();
					
						
					
				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 上传服务器成功的响应
	 * 
	 * @describe 当上传服务器成功后我会保存下来下载地址到share，当点击保存时会将用户信息中的memhead设置为文件名
	 */
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == WIN) {
				back = (String) msg.obj;
				try {
					JSONObject json = new JSONObject(back);
					if (json.getBoolean("status") == true) {
						String name = (String) json.get("newName");// 获取文件名
						String path = (String) json.get("photoPath");
						String url = path + "/" + name;
					
							SharedPreferences share = context.getSharedPreferences("tupiao",context.MODE_PRIVATE);
							Editor edit = share.edit();
							// 保存的是上传的图片的返回名称
							edit.putString("memhead", name);
							CenterInfoChangeActivity.name = name;
							edit.commit();
							((CenterInfoChangeActivity) context)
									.setMemberData();
					
						Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT)
								.show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	};

	/**
	 * 从文件上传图片到服务器
	 * 
	 * @describe 在线程中调用该方法，本类中有全局的路径变量是最新头像路径，通过网络连接和流上传数据到 服务器
	 */
	public void uploadFile() {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + newName + "\"" + end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */// 读入响应
			FileInputStream fStream = new FileInputStream(uploadFile);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = fStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			Message msg = new Message();
			msg.what = WIN;
			msg.obj = b.toString();
			handler.sendMessage(msg);
			ds.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除了上传到服务器意外的本文件夹下的所有文件
	 */
	public void deleteExtra() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File sdcardPath = Environment.getExternalStorageDirectory();
			File dir = new File(sdcardPath, "imagefile");// 在该目录下创建文件
			File[] file = dir.listFiles();
			for (int i = 0; i < file.length; i++) {
				String name = file[i].getName();
				if (name.equals(uploadFile)) {
				} else {
					file[i].delete();
				}
			}
		}
	}
}
